package me.flyray.crm.core.biz;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.flyray.common.msg.ResponseCode;
import me.flyray.crm.core.entity.PayChannelConfig;
import me.flyray.crm.core.entity.PayChannelFeeConfig;
import me.flyray.crm.core.mapper.PayChannelConfigMapper;
import me.flyray.crm.core.mapper.PayChannelFeeConfigMapper;
import me.flyray.crm.facade.request.AddPayChannelConfigRequest;
import me.flyray.crm.facade.request.QueryPayChannelConfigRequest;
import me.flyray.crm.facade.request.UpdatePayChannelConfigRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import me.flyray.common.biz.BaseBiz;
import me.flyray.common.msg.TableResultResponse;
import me.flyray.common.util.EntityUtils;
import me.flyray.common.util.Query;

import lombok.extern.slf4j.Slf4j;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

/**
 * 平台（商户）支付通道配置
 *
 * @author centerroot
 * @email ${email}
 * @date 2018-07-16 10:15:50
 */
@Slf4j
@Service
public class PayChannelConfigBiz extends BaseBiz<PayChannelConfigMapper, PayChannelConfig> {

	@Autowired
	private PayChannelConfigMapper payChannelConfigMapper;
	@Autowired
	private PayChannelFeeConfigMapper payChannelFeeConfigMapper;

	/***
	 * 新增平台/商户支付通道配置
	 */
	public Map<String, Object> add(AddPayChannelConfigRequest addPayChannelConfigRequest) {
		log.info("【新增平台/商户支付通道配置】   请求参数：{}", EntityUtils.beanToMap(addPayChannelConfigRequest));
		Map<String, Object> respMap = new HashMap<String, Object>();
		PayChannelConfig payChannelConfig = new PayChannelConfig();
		BeanUtils.copyProperties(addPayChannelConfigRequest, payChannelConfig);
		payChannelConfig.setStatus("0");// 状态 0：开启 1：关闭
		payChannelConfig.setCreateTime(new Date());
		PayChannelConfig queryParam = new PayChannelConfig();
		queryParam.setPlatformId(payChannelConfig.getPlatformId());
		queryParam.setMerchantId(payChannelConfig.getMerchantId());
		queryParam.setMerchantType(payChannelConfig.getMerchantType());
		queryParam.setPlatformId(payChannelConfig.getPayChannelNo());
		List<PayChannelConfig> payChannelConfiglist = mapper.select(queryParam);
		if (null != payChannelConfiglist && payChannelConfiglist.size() > 0) {
			respMap.put("code", ResponseCode.PAY_CHANNEL_CONFIG_ISEXIST.getCode());
			respMap.put("message", ResponseCode.PAY_CHANNEL_CONFIG_ISEXIST.getMessage());
			log.info("【新增平台/商户支付通道配置】   响应参数：{}", respMap);
			return respMap;
		}
		try {
			if (payChannelConfigMapper.insertSelective(payChannelConfig) > 0) {
				respMap.put("code", ResponseCode.OK.getCode());
				respMap.put("message", ResponseCode.OK.getMessage());
				log.info("【新增平台/商户支付通道配置】   响应参数：{}", respMap);
				return respMap;
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.info("【新增平台/商户支付通道配置】 报错：" + e.getMessage());
			respMap.put("code", ResponseCode.SERVICE_NOT_AVALIABLE.getCode());
			respMap.put("message", ResponseCode.SERVICE_NOT_AVALIABLE.getMessage());
			log.info("【新增平台/商户支付通道配置】   响应参数：{}", respMap);
			return respMap;
		}
		respMap.put("code", ResponseCode.SERVICE_NOT_AVALIABLE.getCode());
		respMap.put("message", ResponseCode.SERVICE_NOT_AVALIABLE.getMessage());
		log.info("【新增平台/商户支付通道配置】   响应参数：{}", respMap);
		return respMap;
	}

	/**
	 * 修改平台/商户支付通道配置
	 * 
	 */
	public Map<String, Object> update(UpdatePayChannelConfigRequest updatePayChannelConfigRequest) {
		log.info("【修改平台/商户支付通道配置】   请求参数：{}", EntityUtils.beanToMap(updatePayChannelConfigRequest));
		Map<String, Object> respMap = new HashMap<String, Object>();
		PayChannelConfig payChannelConfig = new PayChannelConfig();
		try {
			BeanUtils.copyProperties(updatePayChannelConfigRequest, payChannelConfig);
			payChannelConfig.setId(Integer.valueOf(updatePayChannelConfigRequest.getId()));
			payChannelConfig.setUpdateTime(new Date());
			if (mapper.updateByPrimaryKeySelective(payChannelConfig) > 0) {
				respMap.put("code", ResponseCode.OK.getCode());
				respMap.put("message", ResponseCode.OK.getMessage());
				log.info("【修改平台/商户支付通道配置】   响应参数：{}", respMap);
				return respMap;
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.info("【修改平台/商户支付通道配置】 报错：" + e.getMessage());
			respMap.put("code", ResponseCode.SERVICE_NOT_AVALIABLE.getCode());
			respMap.put("message", ResponseCode.SERVICE_NOT_AVALIABLE.getMessage());
			log.info("【修改平台/商户支付通道配置】   响应参数：{}", respMap);
			return respMap;
		}
		respMap.put("code", ResponseCode.SERVICE_NOT_AVALIABLE.getCode());
		respMap.put("message", ResponseCode.SERVICE_NOT_AVALIABLE.getMessage());
		log.info("【修改平台/商户支付通道配置】   响应参数：{}", respMap);
		return respMap;
	}

	/**
	 * 查询平台/商户支付通道配置列表
	 */
	public Map<String, Object> queryList(QueryPayChannelConfigRequest queryPayChannelConfigRequest) {
		log.info("【查询平台/商户支付通道配置】   请求参数：{}", EntityUtils.beanToMap(queryPayChannelConfigRequest));
		Map<String, Object> respMap = new HashMap<String, Object>();
		PayChannelConfig payChannelConfig = new PayChannelConfig();
		String platformId = queryPayChannelConfigRequest.getPlatformId();
		String merchantId = queryPayChannelConfigRequest.getMerchantId();
		int page = queryPayChannelConfigRequest.getPage();
		int limit = queryPayChannelConfigRequest.getLimit();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("page", page);
		params.put("limit", limit);
		Query query = new Query(params);
		Page<Object> result = PageHelper.startPage(query.getPage(), query.getLimit());
		Example example = new Example(PayChannelConfig.class);
		Criteria criteria = example.createCriteria();
		if (!StringUtils.isEmpty(platformId)) {
			criteria.andEqualTo("platformId", platformId);
		}
		if (!StringUtils.isEmpty(merchantId)) {
			criteria.andEqualTo("merchantId", merchantId);
		}
		List<PayChannelConfig> list = mapper.selectByExample(example);
		TableResultResponse<PayChannelConfig> table = new TableResultResponse<PayChannelConfig>(result.getTotal(), list);
		respMap.put("body", table);
		respMap.put("code", ResponseCode.OK.getCode());
		respMap.put("message", ResponseCode.OK.getMessage());
		log.info("【查询客户基础信息列表】   响应参数：{}", respMap);
		return respMap;
	}
	
	/**
	 * 查询支付通道
	 * 先根据商户号和支付通道参数查询，若为空，再根据平台编号查询支付通道
	 * @param request
	 * @return
	 */
	public PayChannelConfig getPayChannelConfig(PayChannelConfig request){
		
		//根据商户号和支付通道参数查询
		PayChannelConfig payChannelConfigBymer = new PayChannelConfig();
		payChannelConfigBymer.setPayChannelNo(request.getPayChannelNo());
		payChannelConfigBymer.setPlatformId(request.getPlatformId());
		if(!StringUtils.isEmpty(request.getMerchantId())){
			payChannelConfigBymer.setMerchantId(request.getMerchantId());
		}
		payChannelConfigBymer.setMerchantType("CUST01");//商户
		PayChannelConfig selectOneBymer = payChannelConfigMapper.selectOne(payChannelConfigBymer);
		if(null == selectOneBymer){
			//根据平台编号和支付通道参数查询
			PayChannelConfig payChannelConfigByplat = new PayChannelConfig();
			payChannelConfigByplat.setPayChannelNo(request.getPayChannelNo());
			payChannelConfigByplat.setPlatformId(request.getPlatformId());
			payChannelConfigByplat.setMerchantType("CUST00");//平台
			PayChannelConfig selectOneByplat = payChannelConfigMapper.selectOne(payChannelConfigByplat);
			return selectOneByplat;
		}else{
			return selectOneBymer;
		}
	}
	
	/**
	 * 商户通道手续费计算
	 * @param request
	 * @return
	 */
	public Map<String, Object> getPayChannelFee(PayChannelConfig request, String payAmt){
		
		//根据商户号和支付通道参数查询
		PayChannelConfig payChannelConfigBymer = new PayChannelConfig();
		payChannelConfigBymer.setPayChannelNo(request.getPayChannelNo());
		payChannelConfigBymer.setPlatformId(request.getPlatformId());
		if(!StringUtils.isEmpty(request.getMerchantId())){
			payChannelConfigBymer.setMerchantId(request.getMerchantId());
		}
		payChannelConfigBymer.setMerchantType("CUST01");//商户
		PayChannelConfig selectOneBymer = payChannelConfigMapper.selectOne(payChannelConfigBymer);
		if(null == selectOneBymer){
			//根据平台编号和支付通道参数查询
			PayChannelConfig payChannelConfigByplat = new PayChannelConfig();
			payChannelConfigByplat.setPayChannelNo(request.getPayChannelNo());
			payChannelConfigByplat.setPlatformId(request.getPlatformId());
			payChannelConfigByplat.setMerchantType("CUST00");//平台
			selectOneBymer = payChannelConfigMapper.selectOne(payChannelConfigByplat);
		}
		
		Map<String, Object> result = new HashMap<String, Object>();
		if(null == selectOneBymer){
			result.put("code", ResponseCode.PAYCHANNEL_CONFIGURATION_NOTEXIST.getCode());
			result.put("message", ResponseCode.PAYCHANNEL_CONFIGURATION_NOTEXIST.getMessage());
			result.put("success", false);
		}else{
			String feeCode = selectOneBymer.getFeeCode();
			if(StringUtils.isEmpty(feeCode)){
				result.put("fee", "0.00");
			}else{
				PayChannelFeeConfig payChannelFeeConfig = new PayChannelFeeConfig();
				payChannelFeeConfig.setFeeCode(feeCode);
				PayChannelFeeConfig selectPayChannelFeeConfig = payChannelFeeConfigMapper.selectOne(payChannelFeeConfig);
				if(null == selectPayChannelFeeConfig){
					result.put("fee", "0.00");
				}else{
					String billingMethod = selectPayChannelFeeConfig.getBillingMethod();
					if("00".equals(billingMethod)){
						//固定收费
						result.put("fee", String.valueOf(selectPayChannelFeeConfig.getFeeAmt()));
					}else if("01".equals(billingMethod)){
						//比例收费
						BigDecimal feeRatio = selectPayChannelFeeConfig.getFeeRatio();
						BigDecimal payAmtDecimal = new BigDecimal(payAmt);
						result.put("fee", String.valueOf(payAmtDecimal.multiply(feeRatio)));
						result.put("feeRatio", String.valueOf(selectPayChannelFeeConfig.getFeeRatio()));
					}
					result.put("billingMethod", billingMethod);
				}
			}
			result.put("code", ResponseCode.OK.getCode());
			result.put("message", ResponseCode.OK.getMessage());
			result.put("success", true);
		}
		return result;
	}

}